const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const babel = require('gulp-babel');
const connect = require('gulp-connect');
const cssnano = require('gulp-cssnano');
const less = require('gulp-less');
const px2rpx = require('gulp-px2rpx');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const cached = require('gulp-cached');
const del = require('del');

const PATTERN_LESS = ['./src/**/*.less'];
const PATTERN_JS = ['./src/**/*.js'];
const PATTERN_GLOBAL = [
    './src/**/*.*',
    '!./src/**/*.less',
    '!./scr/**/node_modules',
    '!./src/**/*.html',
];

gulp.task('less', () =>
    gulp
        .src(PATTERN_LESS)
        .pipe(less())
        .pipe(autoprefixer())
        .pipe(
            cssnano({
                zindex: false,
                autoprefixer: false,
                svgo: false,
                discardComments: {
                    removeAll: true,
                },
            })
        )
        .pipe(
            px2rpx({
                screenWidth: 375, // 设计稿屏幕, 默认750
                wxappScreenWidth: 750, // 微信小程序屏幕, 默认750
                remPrecision: 6, // 小数精度, 默认6
            })
        )
        .pipe(
            rename((path) => {
                path.extname = '.wxss';
            })
        )
        .pipe(gulp.dest('./dist/')) // 将打包好的文件存储在指定的位置中
        .pipe(connect.reload())
);

gulp.task('js', () =>
    gulp
        .src(PATTERN_JS)
        .pipe(
            babel({
                presets: ['@babel/env'],
            })
        )
        .pipe(gulp.dest('./dist/'))
        .pipe(connect.reload())
);

gulp.task('copy_files', () =>
    gulp.src(PATTERN_GLOBAL).pipe(cached('copy_files')).pipe(gulp.dest('./dist/'))
);

gulp.task('clean', (cd) => {
    del(['dist']);
    cd();
});

gulp.task('default', gulp.series(['js', 'less', 'copy_files']));

gulp.task('build', gulp.series(['default']), () => {
    connect.server({
        root: './dist/', // 指定打包后的文件夹
        livereload: true, // 实时刷新
    });
});

gulp.task('watch', () => {
    gulp.watch(PATTERN_LESS, gulp.series('less'));
    gulp.watch(PATTERN_JS, gulp.series('js'));
    gulp.watch(PATTERN_GLOBAL, gulp.series('copy_files'));
});
